import HttpUtils from "../../util/http_utils"
import ApiResult from "../../common/api_result"
import SystemConstants from "../../constant/system_constants"
import UserUtils from "../../util/user_utils"
import ApiConstants from "../../constant/api_constants"
import {LoginReq, LoginRespState} from "./models"
import ObjectUtils from "../../util/object_utils"

export default {
	data() {
		return {
			form: null
		}
	},
	// beforeCreate()是在虚拟dom创建前调用，而created()是虚拟dom创建后创建，但是还没有插入到dom树，所以可以用这个钩子
	async created() {
		if (UserUtils.hasLogin()) {
			await this.$router.push(this.$route.query.redirect || '/')
		}
		this.form = this.$form.createForm(this)
	},
	methods: {
		async handleSubmit(e) {
			e.preventDefault()
			// 先验证表单
			await this.form.validateFields(async (err, formData) => {
				if (!err) {
					let req = new LoginReq(formData)
					console.log('login req:' + JSON.stringify(req))
					// 注意，这里的body不能直接写body: req
					let resp = await HttpUtils.postAsync(ApiConstants.LOGIN_API, {body: JSON.stringify(req)})
					//let result = new ApiResult(resp)
					let result = ObjectUtils.create(ApiResult, resp);
					console.log('login resp:' + JSON.stringify(result))
					if (result.isSuccess()) {
						let state = new LoginRespState(result.state);
						if (req.remember === true) {
							localStorage.setItem(SystemConstants.SYS_STORAGE_TOKEN_KEY, state.data)
						} else {
							sessionStorage.setItem(SystemConstants.SYS_STORAGE_TOKEN_KEY, state.data)
						}
						// noinspection ES6MissingAwait
						this.$message.success('登录成功', 1)
						// 在router里定义了redirect，但是仍然需要自己手动触发
						await this.$router.push(this.$route.query.redirect || '/')
					} else {
						// noinspection ES6MissingAwait
						this.$message.error('登录失败：' + result.message, 1)
					}
				}
			});
		},
	},
};